#coding:utf-8
import flask
import os
import sqlite3
import json
import time


def get_quote(num):
	conn = sqlite3.connect('quotes.db')
	cur = conn.cursor()
	cur.execute('select * from quotes where id=?;',[num])
	row = cur.fetchone()
	if row:
		res = dict(zip(['id','text','author','link','range'],row))
	else:
		res = None
	conn.close()
	return res

def get_count():
	conn = sqlite3.connect('quotes.db')
	cur = conn.cursor()
	cur.execute('select count(*) from quotes')
	return cur.fetchone()[0]

app = flask.Flask(__name__)

@app.route("/")
def return_help():
	return flask.render_template('index.html')

@app.route("/visitors_statistics") # send get request here to count visitors
def count_visitors():
	if 'username' in flask.session:
		user = flask.session['username']
	else:
		user = None
	os.system('notify-send -t 500 "We have a visitor!" "Yea! User:'+str(user)+'"')
	#os.system('mocp -p')
	return "Вас порахували! :) <br /> А взагалі, то на сервері просто вилізло повідомлення. Треба буде потім написати код покраще, який зміг би вичисляти по IP, і подібне. <br /> Ви:" + str(user)

@app.route("/get<num>")
def return_quote(num):
	quote = get_quote(num)
	return json.dumps(quote)

@app.route("/count")
def return_count():
	return json.dumps(get_count())

@app.route("/login",methods=['GET','POST'])
def login():
	if flask.request.method == 'POST':
		flask.session['username'] = flask.request.form['username']
		return json.dumps(flask.session['username'])
	if 'username' in flask.session:
		return json.dumps(flask.session['username'])
	return json.dumps(None)

@app.route('/logout')
def logout():
	flask.session.pop('username', None)
	return ""

app.secret_key = 'Really really secret phraze: alohomora!!! and avada-kedavra!!!! die hackers, die!'

if __name__ == "__main__":
	app.run(host='0.0.0.0',debug=True)
